package server;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.*;


import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.ServerAddress;

import data.Data;
import data.Utils;

import java.util.*;
import java.util.regex.Pattern;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class AlexaUpdate extends Thread{
	DBObject domain;
	String sock;
	public AlexaUpdate(DBObject domain,String sock)
	{
		this.domain=domain;
		this.sock=sock;
		this.start();
	}
	@SuppressWarnings("unused")
	public void run()
	{
		try {
			DBCollection coll = Data.data("domain");
			DBObject domains = coll.findOne(new BasicDBObject("name",Utils.returnSubDomainTo(domain.get("name").toString())));
			if(!Utils.checkSubDomain(domain.get("name").toString()) || Pattern.matches("[\\w\\W]*wordpress.com$", domain.get("name").toString())|| Pattern.matches("[\\w\\W]*blogspot.com$", domain.get("name").toString()) || domains ==null)
			{
				Random random = new Random();
				
				Socket sockket = new Socket("alexa.com", 80, InetAddress.getByName(sock), random.nextInt(1000)+30000);
	//			Socket sockket = new Socket("www.alexa.com", 80);
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sockket.getOutputStream()));
				
				writer.write("GET /siteinfo/"+domain.get("name")+" HTTP/1.1\r\n");
				writer.write("Host: www.alexa.com\r\n");
				writer.write("Referer: http://5ty.org\r\n");
				
				writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
				writer.write("Connection:	Close\r\n");
				
				
				writer.write("\r\n\r\n");
				writer.flush();
				BufferedReader reader =  new BufferedReader(new InputStreamReader(sockket.getInputStream()));
				String content = "";
				while(1==1)
				{
					String str = reader.readLine();
					if(str==null) break;
					content+=str;
				}
		
				Document doc = Jsoup.parse(content);
	
				// visitor
				String visit = "0";
				if(doc.select(".visitors_percent").select(".avg").size() > 0)
				{
					visit = doc.select(".visitors_percent").select(".avg").last().text().trim();
				}
				// rank
				String ranks = null;
				if(doc.select("#siteStats").select("div").size() > 0)
				{
					ranks = doc.select("#siteStats").select("div").first().text().trim().replace(",","");
				}
				int rank = 0;
				
				try {
					if(ranks != null && !ranks.equals(""))
					{
						rank=Integer.parseInt( ranks );
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				//keywords
				BasicDBObject b_key = new BasicDBObject();
				Elements elements = doc.select("#top-keywords-from-search");
	
				if(elements.size() > 0)
				{
					for (Element element : elements.first().select("u")) {
						
						b_key.put(element.text().trim().replaceAll("[.]+", "&&&"), 1);
					}
				}
				
				domain.put("visit", visit);
				domain.put("pKeyword", b_key);
				domain.put("rank", rank);
			} else {
				if(domains != null)
				{
					domain.put("visit", domains.get("visit"));
					domain.put("pKeyword", domains.get("pKeyword"));
					domain.put("rank", domains.get("rank"));
				} 
			}
			if(domains == null && Utils.checkSubDomain(domain.get("name").toString()))
			{
				try {
					setUp();
					createProducerAndSendAMessage(Utils.returnSubDomainTo(domain.get("name").toString()));
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
//	public static void main( String args[])
//	{
//		
//		Domain domain = new Domain();
//		domain.setName("google.com");
//		new AlexaUpdate(domain);
//	}
	private static ActiveMQConnectionFactory connectionFactory;
    private static Connection connection;
    private static Session session;
    private static Destination destination;
    private static boolean transacted = false;
	private static void setUp() throws JMSException {
         connectionFactory = new ActiveMQConnectionFactory(
                 ActiveMQConnection.DEFAULT_USER,
                 ActiveMQConnection.DEFAULT_PASSWORD,
                 "tcp://y1s.org:61616");
         connection = connectionFactory.createConnection();
         connection.start();
         session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
         destination = session.createQueue("domain");
     }
 
     private static void createProducerAndSendAMessage(String str) throws JMSException {
   	  
         MessageProducer producer = session.createProducer(destination);
         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         TextMessage message = session.createTextMessage(str);
         System.out.println("Sending message: " + message.getText());
         producer.send(message);
         connection.close();
     }
}
